package com.aurora.app.controller;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.aurora.app.constant.Conf;
import com.aurora.app.entity.User;
import com.aurora.app.entity.UserAccount;
import com.aurora.app.entity.WeixinAppToken;
import com.aurora.app.entity.WeixinUserToken;
import com.aurora.app.enums.FakeDelete;
import com.aurora.app.service.UserAccountService;
import com.aurora.app.service.UserService;
import com.aurora.app.service.WeixinAppTokenService;
import com.aurora.app.service.WeixinService;
import com.aurora.app.service.WeixinUserTokenService;
import com.aurora.base.util.EmojiFilter;
import com.aurora.base.util.FingerprintUtil;
import com.aurora.base.util.HttpSend;
import com.aurora.base.util.Utf8Util;


/**
 * 微信的登陆。错误。超时。注销
 * @author Administrator
 *
 */

@Controller
@RequestMapping(value = "api/weixin")
public class WeixinLoginController {
	private final Logger LOG = LoggerFactory.getLogger(this.getClass());
	
	@Resource
	private WeixinAppTokenService weixinAppTokenService;
	@Resource
	private UserService userService ;
	@Resource
	private WeixinUserTokenService weixinUserTokenService;
	//获取access_token
	private static final String authUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

	//拉取用户基本信息
	private static final String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";

	

	@RequestMapping(value="login")
	public ModelAndView login(HttpServletRequest request, HttpSession session, HttpServletResponse response) throws Exception{
		LOG.info("----------正在获取用户授权-------------");
		
		
		String code = request.getParameter("code");
		if(StringUtils.isNotBlank(code)){
			WeixinAppToken weixinAppToken = this.weixinAppTokenService.findById(Conf.USED2_ID);
			if(weixinAppToken==null){
				LOG.info("------------微信权限信息获取错误-----------------");
				ModelAndView err = new ModelAndView("err");
				return err;
			}else{
				String url = authUrl.replaceAll("APPID",weixinAppToken.getAppId()).replaceAll("SECRET", weixinAppToken.getAppSecret()).replaceAll("CODE", code);
				String Result = HttpSend.httpRequestStr(url, "GET", null);
				LOG.info("accessToken环节"+Result);
				JSONObject json = new JSONObject(Result);
				WeixinUserToken weixinUserToken = this.weixinUserTokenService.findByOpenId(json.getString("openid"));
				
				if(weixinUserToken!=null){
					LOG.info("用户曾经登陆过app");
					//更新用户信息
					User user = weixinUserToken.getUser();
					LOG.info("----------updating user info-----------");
					String infoStr = infoUrl.replaceAll("ACCESS_TOKEN", json.getString("access_token")).replaceAll("OPENID",json.getString("openid"));
					String infoResult = HttpSend.httpRequestStr(infoStr, "GET", null);
					LOG.info(infoResult);
					//String info = new String(Base64.decodeBase64(infoResult), "UTF-8");
					JSONObject jsonInfo = new JSONObject(infoResult);
					System.out.println(Utf8Util.setUtf8(jsonInfo.getString("nickname")) );
					user.setNickName(Utf8Util.setUtf8(jsonInfo.getString("nickname")) );
					user.setSex(jsonInfo.getInt("sex"));
					user.setProvince(jsonInfo.getString("province"));
					user.setCity(jsonInfo.getString("city"));
					user.setCountry(jsonInfo.getString("country"));
					user.setHeadimgurl(jsonInfo.getString("headimgurl"));
					this.userService.update(user);
					
					weixinUserToken.setAccessToken(json.getString("access_token"));
					weixinUserToken.setGetRefreshTokenTime(new Date());
					weixinUserToken.setRefreshToken(json.getString("refresh_token"));
					weixinUserToken.setGetRefreshTokenTime(new Date());
					this.weixinUserTokenService.update(weixinUserToken);
				}else{
					LOG.info("------------第一次进入app------------------");
					weixinUserToken = new WeixinUserToken();
					weixinUserToken.setAccessToken(json.getString("access_token"));
					weixinUserToken.setGetRefreshTokenTime(new Date());
					weixinUserToken.setRefreshToken(json.getString("refresh_token"));
					weixinUserToken.setGetRefreshTokenTime(new Date());
					User user = new User();
					user.setOpenid(json.getString("openid"));
					LOG.info("----------正在拉取用户信息-----------");
					String infoStr = infoUrl.replaceAll("ACCESS_TOKEN", json.getString("access_token")).replaceAll("OPENID",json.getString("openid"));
					String infoResult = HttpSend.httpRequestStr(infoStr, "GET", null);
					LOG.info("用户信息==" + infoResult);
					System.out.println("用户信息==" + infoResult);
					JSONObject jsonInfo = new JSONObject(infoResult);
					System.out.println(Utf8Util.setUtf8(jsonInfo.getString("nickname")) );
					user.setNickName(Utf8Util.setUtf8(jsonInfo.getString("nickname")) );
					user.setSex(jsonInfo.getInt("sex"));
					user.setProvince(jsonInfo.getString("province"));
					user.setCity(jsonInfo.getString("city"));
					user.setCountry(jsonInfo.getString("country"));
					user.setHeadimgurl(jsonInfo.getString("headimgurl"));
					this.userService.save(user);
					
					weixinUserToken.setUser(user);
					
					this.weixinUserTokenService.save(weixinUserToken);
					
				}
				System.out.println(json.getString("openid"));
				User user = this.userService.findByOpenid(json.getString("openid"));
				if(user!=null){
					request.getSession().setAttribute("user", weixinUserToken.getUser());
					System.out.println("重定向");
					System.out.println("redirect:"+request.getParameter("state"));
					return new ModelAndView("redirect:"+request.getParameter("state"));
					//return mv;
				}else{
					LOG.info("------------微信用户获取异常-----------------");
					ModelAndView err = new ModelAndView("err");
					return err;
				}
				
			}
		}else{
			LOG.info("------------微信授权失败-----------------");
			ModelAndView err = new ModelAndView("err");
			return err;
		}
	}
	
	@RequestMapping(value="logout")
	public void logout(HttpServletRequest request){
		request.getSession().removeAttribute("user");
		LOG.info("--------------成功注销登陆-------------------");
	}
	
	@RequestMapping(value="error")
	public ModelAndView error(HttpServletRequest request){
		ModelAndView mv = new ModelAndView("error");
		return mv;
	}
}
